<template>
  <div>
    <li>
        <label>
            <input type="checkbox" :checked="todo.completed" @change="changeStatus(todo.id)"/>
            <input 
                type="text" 
                v-show="todo.isEdit" 
                :value="todo.title"
                @blur="handleBlur(todo,$event)"
                @keyup.enter="handleBlur(todo,$event)"
                ref="inputTitle">
            <span v-show="!todo.isEdit">{{ todo.title }}</span>
        </label>
        <button class="btn btn-danger" @click="deleteTodo(todo.id)">删除</button>
        <button v-show="!todo.isEdit" class="btn btn-edit" @click="editTodo(todo)">编辑</button>
        <button v-show="todo.isEdit" class="btn btn-edit" @click="handleBlur(todo,$event)">保存</button>
    </li>
  </div>
</template>

<script>
    import pubSub from 'pubsub-js'
    export default {
        props: ['todo'],
        methods:{
            changeStatus(id){
                this.$bus.$emit('changeStatus',id)
            },
            deleteTodo(id){
                // this.$bus.$emit('deleteTodo',id)
                pubSub.publish('deleteTodo',id)
            },
            editTodo(todo){
                if(Object.prototype.hasOwnProperty.call(todo, 'isEdit')){
                    todo.isEdit = true;
                }else{
                    this.$set(todo, 'isEdit', true); //保证初次加入的时候存在响应式的数据
                }
                //自动获取焦点
                //this.$refs.inputTitle.focus(); //此时你这行代码执行了，但是注意vue并没有重新解析模版(input并没有出现在页面上，dom节点并没有被更新)，它一定要等这个回调函数执行完之后才会去重新渲染模版
                //使用nextTick来解决
                this.$nextTick(() => {
                //这里的回调函数注意是在DOM节点被更新之后才会运行的
                    this.$refs.inputTitle.focus();
                })
                console.log(todo);
            },
            handleBlur(todo,e){
                todo.isEdit = false; //注意我在这里确保你身上一定存在isEdit属性
                if(!e.target.value.trim()) {
                    alert('输入不能为空');
                    return;
                }
                this.$bus.$emit('updateTodo',todo.id,e.target.value)
            }
        }
    }
</script>

<style scoped>
    /*item*/
    li {
        list-style: none;
        height: 36px;
        line-height: 36px;
        padding: 0 5px;
        border-bottom: 1px solid #ddd;
    }

    li label {
        float: left;
        cursor: pointer;
    }

    li label li input {
        vertical-align: middle;
        margin-right: 6px;
        position: relative;
        top: -1px;
    }

    li button {
        float: right;
        display: none;
        margin-top: 3px;
    }

    li:before {
        content: initial;
    }

    li:last-child {
        border-bottom: none;
    }
    li:hover {
        background: #ddd;
    }
    li:hover button{
        display: block;
    }
</style>